package nobu.nakata.nfcfare.resource.impl;

import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.resource.IBusResource;
import nobu.nakata.nfcfare.resource.item.IBusResourceItem;
import nobu.nakata.nfcfare.resource.mapper.BusResourceMapper;
import nobu.nakata.nfcfare.resource.util.ServiceResourceUtil;

import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import com.google.appengine.api.users.User;

public class BusResource extends ServerResource implements IBusResource {
	static private final String KEY_BUS_CODE	= "busCode";
	
	
	@Override
	public IBusResourceItem retrieve() {
		PersistenceManager pm = null;
		try {
			Cache cache = ServiceResourceUtil.makeCache();
			pm = ServiceResourceUtil.makeStorage();			
			User viewer = ServiceResourceUtil.getViewer();
			long busCodeNum = getBusCode();
			if (busCodeNum <= 0)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			BusResourceMapper resourceMapper = new BusResourceMapper(cache, pm, viewer);
			IBusResourceItem result = resourceMapper.findByTrainStationCode(busCodeNum);
			if (result == null)
				throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
			return result;
		} catch(ResourceException e) {
			throw e;
		} catch(Throwable th) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	@Override
	public IBusResourceItem update(IBusResourceItem updateResourceItem) {
		PersistenceManager pm = null;
		try {
			User viewer = ServiceResourceUtil.getViewer();
			if (viewer == null)
				throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN);
			long busCodeNum = getBusCode();
			if (busCodeNum <= 0 || updateResourceItem.getBusCode() != busCodeNum)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			Cache cache = ServiceResourceUtil.makeCache();
			pm = ServiceResourceUtil.makeStorage();
			BusResourceMapper resourceMapper = new BusResourceMapper(cache, pm, viewer);
			if (resourceMapper.findByTrainStationCode(updateResourceItem.getBusCode()) == null)
				throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
			resourceMapper.set(updateResourceItem);
			return updateResourceItem;
		} catch(ResourceException e) {
			throw e;
		} catch(Throwable th) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		} finally {
			if (pm != null)
				pm.close();
		}
	}
	
	
	private long getBusCode() {
		try {
			return Long.parseLong((String) getRequest().getAttributes().get(KEY_BUS_CODE));
		} catch(Throwable th) {
			return 0;
		}
	}
}
